package com.guodi.model.utils;


import com.guodi.core.tool.utils.StringUtil;
import org.apache.commons.lang.StringUtils;

import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.Charset;
import java.sql.Blob;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author daihuojin
 * @DATE 2020/5/21.
 * @description
 */
public class ConvertUtil {

    /**
     * blob转string
     *
     * @param blob
     * @return
     */
    public static String Blob2Str(Blob blob) {
        String result = "";
        if (blob != null) {
            try {
                OutputStream stmt = new ByteArrayOutputStream();
                byte[] tmpByte = new byte[1024 * 4];
                InputStream inpStm = blob.getBinaryStream();
                int readLength = 0;
                do {
                    readLength = inpStm.read(tmpByte);
                    if (readLength != -1) {
                        stmt.write(tmpByte, 0, readLength);
                    }
                } while (readLength != -1);

                stmt.flush();
                result = stmt.toString();
                inpStm.close();
                stmt.close();
            } catch (SQLException e) {
            } catch (IOException e) {
            }
        }
        return result;
    }

    /**
     * date2SQLDate
     *
     * @param d
     * @return
     */
    public static java.sql.Date date2SQLDate(java.util.Date d) {
        return new java.sql.Date(d.getTime());
    }

    public static Timestamp date2SQLDateTime(java.util.Date d) {
        return new Timestamp(d.getTime());
    }

    public static String inputStream2Str(InputStream inpStm) {
        if (inpStm == null) {
            return "";
        }
        String result = "";
        try {
            ByteArrayOutputStream stmt = new ByteArrayOutputStream();
            byte[] tmpByte = new byte[1024 * 4];
            int readLength = 0;
            do {
                readLength = inpStm.read(tmpByte);
                if (readLength != -1) {
                    stmt.write(tmpByte, 0, readLength);
                }
            } while (readLength != -1);

            stmt.flush();
            result = new String(stmt.toByteArray(), "utf-8");
//            result = new String(stmt.toByteArray());
            inpStm.close();
            stmt.close();
        } catch (IOException e) {
        }
        return result;
    }

    /**
     * IsLeapYear
     *
     * @param y
     * @return
     */
    private static boolean IsLeapYear(int y) {
        return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
    }

    /**
     * @param str
     * @return
     */
    private static boolean IsYearOrMonthOrDay(String str) {
        String regEx = "\\d*$";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.find();
    }

    /**
     * @param stream
     */
    public static String outputStream2Str(OutputStream stream) {
        return null;
    }


    /**
     * Str2InputStream
     *
     * @param str
     * @return
     */
    public static InputStream str2InputStream(String str) {
        return new ByteArrayInputStream(str.getBytes());
    }

    /**
     * 判断字符串是否是自启
     *
     * @param str
     * @return
     */
    public static boolean StrIsDate(String str) {
        String[] numArray = str.split("-");
        boolean result = false;
        if (numArray.length == 3) {
            result = IsYearOrMonthOrDay(numArray[0])
                    && IsYearOrMonthOrDay(numArray[1])
                    && IsYearOrMonthOrDay(numArray[2]);
            if (result) {
                try {
                    int year = Integer.parseInt(numArray[0]);
                    int month = Integer.parseInt(numArray[1]);
                    int day = Integer.parseInt(numArray[2]);

                    result = year > 0 && month > 0 && day > 0 && month <= 12
                            && day <= 31;

                    if (result) {
                        if (month == 1 || month == 3 || month == 5
                                || month == 7 || month == 8 || month == 10
                                || month == 12) {
                            result = day > 0 && day <= 31;
                        } else if (month == 2) {
                            if (IsLeapYear(year)) {
                                result = day <= 29;
                            } else {
                                result = day <= 28;
                            }
                        } else {
                            result = day <= 30;
                        }
                    }
                } catch (NumberFormatException e) {
                    result = false;
                }
            }
        }

        return result;
    }


    /**
     * StrIsInteger判断字符串是否是integer
     *
     * @param str
     * @return
     */
    public static boolean strIsInteger(String str) {
        String regEx = "^[-+]?\\d*$";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.find();
    }

    /**
     * 判断字符串是否是数字
     *
     * @param str
     * @return
     */
    public static boolean strIsNumber(String str) {
        String regEx = "^((\\d?)|(([-+]?\\d+\\.?\\d*)|([-+]?\\d*\\.?\\d+))|(([-+]?\\d+\\.?\\d*\\,\\ ?)*([-+]?\\d+\\.?\\d*))|(([-+]?\\d*\\.?\\d+\\,\\ ?)*([-+]?\\d*\\.?\\d+))|(([-+]?\\d+\\.?\\d*\\,\\ ?)*([-+]?\\d*\\.?\\d+))|(([-+]?\\d*\\.?\\d+\\,\\ ?)*([-+]?\\d+\\.?\\d*)))$";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        if (m.find()) {
            if (str.indexOf(",") == -1 && str.indexOf("，") == -1 && !str.equals("0")) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * StrIsTime 判断字符串是否是时间
     *
     * @param str
     * @return
     */
    public static boolean StrIsTime(String str) {
        String regEx = "^(([0-1]?[0-9])|([2][0-3])):([0-5]?[0-9])(:([0-5]?[0-9]))?$";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.find();
    }

    /**
     * tryStrToFloat
     *
     * @param str
     * @param defaultValue
     * @return
     */
    public static float tryStrToFloat(String str, float defaultValue) {
        float result = defaultValue;
        try {
            if ("∞".equals(str)) {
                result = Float.MAX_VALUE;
            } else {
                result = (new Float(str)).floatValue();
            }

        } catch (Exception e) {

        }
        return result;
    }

    /**
     * tryStrToFloat 字符串转double
     *
     * @param str
     * @param defaultValue
     * @return
     */
    public static double tryStrToDouble(String str, double defaultValue) {
        double result = defaultValue;
        try {
            if ("∞".equals(str)) {
                result = Double.MAX_VALUE;
            } else {
                result = (new Double(str)).doubleValue();
            }
        } catch (Exception e) {

        }
        return result;
    }

    /**
     * tryObjToDouble
     *
     * @param str
     * @param defaultValue
     * @return
     */
    public static double tryObjToDouble(Object str, double defaultValue) {
        double result = defaultValue;
        try {
            if ("∞".equals(str)) {
                result = Double.MAX_VALUE;
            } else {
                result = (new Double(str.toString())).doubleValue();
            }
        } catch (Exception e) {

        }
        return result;
    }

    /**
     * tryStrToInt
     *
     * @param str
     * @param defaultValue
     * @return
     */
    public static int tryStrToInt(String str, int defaultValue) {
        int result = defaultValue;
        try {
            if ("∞".equals(str)) {
                result = Integer.MAX_VALUE;
            } else {
                result = (new Integer(str)).intValue();
            }

        } catch (Exception e) {

        }
        return result;
    }

    /**
     * tryStrToLong
     *
     * @param str
     * @param defaultValue
     * @return
     */
    public static long tryStrToLong(String str, long defaultValue) {
        long result = defaultValue;
        try {
            result = (new Long(str)).longValue();
        } catch (Exception e) {

        }
        return result;
    }


    /**
     * @param obj
     * @param defaultValue
     * @return
     */
    public static int tryObjToInt(Object obj, int defaultValue) {
        int result = defaultValue;
        try {
            if (obj != null) {
                if ("∞".equals(obj.toString())) {
                    result = Integer.MAX_VALUE;
                } else {
                    result = (new Integer(obj.toString())).intValue();
                }
            }

        } catch (Exception e) {

        }
        return result;
    }

    /**
     * 将字符串转话为字节流
     *
     * @param value
     * @return
     */
    public static byte[] str2Bytes(final String value) {
        if (StringUtils.isEmpty(value)) {
            return null;
        }
        return value.getBytes(Charset.forName("utf-8"));
    }

    /**
     * 判断字符串是否为空
     *
     * @param value
     * @return
     */
    public static boolean isnull(Object value) {
        return value == null || value.toString().length() == 0;
    }

    /**
     * 字符串转数字
     *
     * @param value
     * @return
     */
    public static Object str2Number(String value) {
        if (strIsNumber(value)) {
            if (value.indexOf(".") > -1) {
                return (new Double(value)).doubleValue();
            } else {
                return (new Integer(value)).intValue();
            }
        } else {
            return null;
        }
    }

    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("-?[0-9]+(\\.[0-9]+)?");
        return pattern.matcher(str).matches();
    }

    /**
     * 描述 : Object转byte[]. <br>
     *
     * @param obj
     * @return
     */
    public static byte[] toByteArray(Object obj) {
        byte[] bytes = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);
            oos.flush();
            bytes = bos.toByteArray();
            oos.close();
            bos.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return bytes;
    }

    /**
     * 描述 :  byte[]转Object . <br>
     *
     * @param bytes
     * @return
     */
    public static Object toObject(byte[] bytes) {
        Object obj = null;
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bis);
            obj = ois.readObject();
            ois.close();
            bis.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }
        return obj;
    }

    /**
     * @描述:保留数字后几位小数
     * @入参:
     * @出参:
     * @作者: 戴伙进
     * @日期: 2020/5/25 16:41
     **/
    public static String formatNumber(double value, int num) {
        BigDecimal bigDecimal = new BigDecimal(value);
        bigDecimal = bigDecimal.setScale(num, RoundingMode.HALF_DOWN);
        return bigDecimal.toString();
    }

    /**
     * @描述:String 位数不够后面补零
     * @入参:
     * @出参:
     * @作者: 戴伙进
     * @日期: 2020/7/1 10:56
     **/
    public static String addZeroForStr(String str, int strLength) {
        int strLen = str.length();
        if (strLen < strLength) {
            while (strLen < strLength) {
                StringBuffer sb = new StringBuffer();
                sb.append(str).append("0");
                str = sb.toString();
                strLen = str.length();
            }
        }
        return str;
    }


    /**
     * @描述: 格式数据，保留小数
     * @入参: len：小数长度
     * @出参:
     * @作者: 汤厚韬
     * @日期: 2021/1/26
     **/
    public static Double formatNum(Object data, Integer len) {
        if (data == null || StringUtils.isBlank(String.valueOf(data))) {
            return null;
        }
        Double tmp = Double.valueOf(String.valueOf(data));
        String rule = "%.2f";
        if (len != null) {
            rule = "%." + len + "f";
        }
        String dataStr = String.format(rule, tmp);
        return Double.valueOf(dataStr);
    }

    public static String ToCH(int intInput) {
        String si = String.valueOf(intInput);
        String sd = "";
        if (si.length() == 1) {
            sd += GetCH(intInput);
            return sd;
        } else if (si.length() == 2) {
            if (si.substring(0, 1).equals("1")) {
                sd += "十";
            } else {
                sd += (GetCH(intInput / 10) + "十");
            }
            sd += ToCH(intInput % 10);
        } else if (si.length() == 3) {
            sd += (GetCH(intInput / 100) + "百");
            if (String.valueOf(intInput % 100).length() < 2) {
                sd += "零";
            }
            sd += ToCH(intInput % 100);
        } else if (si.length() == 4) {
            sd += (GetCH(intInput / 1000) + "千");
            if (String.valueOf(intInput % 1000).length() < 3) {
                sd += "零";
            }
            sd += ToCH(intInput % 1000);
        } else if (si.length() == 5) {
            sd += (GetCH(intInput / 10000) + "万");
            if (String.valueOf(intInput % 10000).length() < 4) {
                sd += "零";
            }
            sd += ToCH(intInput % 10000);
        }
        return sd;
    }

    private static String GetCH(int input) {
        String sd = "";
        switch (input) {
            case 1:
                sd = "一";
                break;
            case 2:
                sd = "二";
                break;
            case 3:
                sd = "三";
                break;
            case 4:
                sd = "四";
                break;
            case 5:
                sd = "五";
                break;
            case 6:
                sd = "六";
                break;
            case 7:
                sd = "七";
                break;
            case 8:
                sd = "八";
                break;
            case 9:
                sd = "九";
                break;
        }
        return sd;
    }

    /**
     * 功能描述
     *
     * @描述 移除字符串最后的0，省级，市级，区县级
     * @入参
     * @出参
     * @作者 dhj
     * @日期 2023/9/22 14:49
     */
    public static String removeLastZero(String inputStr) {
        String retStr = inputStr;
        if (!StringUtil.isEmpty(inputStr)) {
            //省级
            if (inputStr.endsWith("0000")) {
                retStr = inputStr.substring(0, inputStr.length() - 4);
            } else if (inputStr.endsWith("00")) {
                //市级
                retStr = inputStr.substring(0, inputStr.length() - 2);
            }
        }
        return retStr;
    }

}
